//
//  UIImageView+FCDownload.m
//  辅城
//
//  Created by jianhong zhang on 2017/9/20.
//  Copyright © 2017年 吴 剑川. All rights reserved.
//

#import "UIImageView+WJCDownload.h"
#import "WJCDefine.h"
#import "FCPhotoBrowserTool.h"
#import <objc/runtime.h>
@implementation UIImageView (FCDownload)
    // 当系统加载运行时的时候会调用的方法 在这里做交换方法
+(void)load
{
        // 获取 UIimageview 类的实力方法：setImage
//    Method originalMethod = class_getInstanceMethod([self class], @selector(setImage:));
//        //获取 UIimageview 类的实力方法：xw_setimage
//    Method swizzledMethod = class_getInstanceMethod([self class], @selector(fc_setimage:));
//        // 交换
//    method_exchangeImplementations(originalMethod, swizzledMethod);
//    
}
-(void)fc_setimage:(UIImage *)image
{
    if (![image isKindOfClass:[UIImage class]]) {
        if ([image isKindOfClass:[NSString class]]) {
            NSString *str=(NSString*)image;
            if (str.length>0) {
                [self fc_setOriginImage:str placeholder:[WJCDeployModel getDeployWithDeployKey:WJCDeployHeadImage] completed:nil];
            }
            else{
                [self fc_setimage:[WJCDeployModel getDeployWithDeployKey:WJCDeployHeadImage]];
            }
        }else{
            [self fc_setimage:[WJCDeployModel getDeployWithDeployKey:WJCDeployHeadImage]];
        }
    }else{
        [self fc_setimage:image];
    }
}

/**
 * 加载图片，加七牛参数
 */
- (void)fc_setOriginImage:(NSString *)originImageURL placeholder:(UIImage *)placeholder completed:(void (^)(UIImage *))completedBlock
{
    [self layoutIfNeeded];

    if(!originImageURL||originImageURL.length<1){
        self.image=placeholder;
        return;
    }
    if ([originImageURL isKindOfClass:[UIImage class]]) {
        self.image=(UIImage*)originImageURL;
        return;
    }
    if ([originImageURL isKindOfClass:[NSNull class]]) {
        self.image=nil;
        return;
    }
    SDWebImageDownloader *manager = [SDWebImageDownloader sharedDownloader];
    NSArray *array = [saveSandBox getCookie];
    if (array&&array.count>0) {
        NSMutableString *str=[NSMutableString new];
        for (NSHTTPCookie *cookie in array) {
            [str appendString:[NSString stringWithFormat:@"%@=%@;",cookie.name,cookie.value]];
        }
        
    [manager setValue:str forHTTPHeaderField:@"Cookie"];
    }
    
    [manager setValue:@"Code=iOS" forHTTPHeaderField:@"Client-Info"];
    [manager setValue:[NSString stringWithFormat:@"Platform=iOS;VersionName=%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] forHTTPHeaderField:@"client-msg"];
    [manager setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"] forHTTPHeaderField:@"Accept-Language"];
    [manager setValue:@"true" forHTTPHeaderField:@"useClientLang"];
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"]){
        [manager setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"] forHTTPHeaderField:@"Accept-Language"];
    }
    
    if ([originImageURL containsString:@"files.fccn.cc"] || [originImageURL containsString:@"filesdev.fccn.cc"]|| [originImageURL containsString:@"clouddn.com"] )
    {
   
        if ([originImageURL containsString:@"?imageView2/"]) {
            
        } else if ([originImageURL containsString:@"?"]) {
            if (self.frame.size.width < WJCScreenW*0.5){
                
                long imageW = self.frame.size.width * 2;
                long imageH = self.frame.size.height * 2;
                while (imageW<WJCScreenW*0.5) {
                     imageW =imageW * 2;
                    imageH = imageH * 2;
                }
                originImageURL = [NSString stringWithFormat:@"%@&imageView2/1/w/%zd/h/%zd",originImageURL,imageW,imageH];
                
            } else {
                originImageURL = [NSString stringWithFormat:@"%@&imageView2/0/q/45",originImageURL];
            }
            
        } else if (self.frame.size.width < WJCScreenW*0.6){
                  long imageW = self.frame.size.width * 2;
                  long imageH = self.frame.size.height * 2;
            if(self.frame.size.width>0){
            while (imageW<WJCScreenW*0.6) {
                imageW =imageW * 2;
                imageH = imageH * 2;
            }
            }else{
                imageW=WJCScreenW*0.7;
                imageH=WJCScreenW*0.7;
            }
            originImageURL = [NSString stringWithFormat:@"%@?imageView2/1/w/%zd/h/%zd",originImageURL,imageW,imageH];
//            WJCLog(@"url: %@",originImageURL);
            
        } else {
            
            originImageURL = [NSString stringWithFormat:@"%@?imageView2/0/q/35",originImageURL];
        }
        
    } else if ([originImageURL containsString:@"aliyuncs.com"]){
         originImageURL = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,m_fill,h_250,w_250",originImageURL];
        
    }
    
//    if ([originImageURL hasPrefix:@"//"]) {//是否@"//"开头
//        //请求Url
//        originImageURL = [NSMutableString stringWithFormat:@"https:%@",originImageURL];
//    }
    
    // 转义URL
    originImageURL = [originImageURL  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholder completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (completedBlock) {
            completedBlock(image);
        }
    }];
}
-(void)fc_setImageWidthAndHeightWithImage:(NSString *)originImageURL placeholder:(UIImage *)placeholder completed:(void (^)(UIImage *))completedBlock{
    if ([originImageURL isKindOfClass:[UIImage class]]) {
        self.image=(UIImage*)originImageURL;
        return;
    }
    NSString *QiNiuUrl = [WJCDeployModel getDeployWithDeployKey:WJCDeployAPIHeadUrl];
    if (!originImageURL||[originImageURL isEqual:[NSNull null]]) {
        self.image=placeholder;
        return;
    }
    SDWebImageDownloader *manager = [SDWebImageDownloader sharedDownloader];
    
    [manager setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"] forHTTPHeaderField:@"Accept-Language"];
    [manager setValue:@"true" forHTTPHeaderField:@"useClientLang"];
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"]){
        [manager setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"] forHTTPHeaderField:@"Accept-Language"];
    }
    if ([originImageURL containsString:@"files.fccn.cc"] || [originImageURL containsString:@"filesdev.fccn.cc"]|| [originImageURL containsString:@"clouddn.com"] || [originImageURL containsString:QiNiuUrl])
        {
        if ([originImageURL containsString:@"?imageView2/"]) {
            
        }
         else if ([originImageURL containsString:@"?"]) {
                int imageW = self.frame.size.width ;
                int imageH = self.frame.size.height ;
            if (imageW<80) {
                imageW=120;
                imageH=120;
            }
            if (imageW>WJCScreenW*0.6) {
                 originImageURL = [NSString stringWithFormat:@"%@&imageView2/1/w/%d/h/%d",originImageURL,imageW,imageH];
            }else{
            originImageURL = [NSString stringWithFormat:@"%@&imageView2/1/w/%d/h/%d",originImageURL,imageW*2,imageH*2];
            }
        }
        else {
            int imageW = self.frame.size.width ;
            int imageH = self.frame.size.height;
            if (imageW<80) {
                imageW=120;
                imageH=120;
            }
            if (imageW>WJCScreenW) {
                originImageURL = [NSString stringWithFormat:@"%@?imageView2/1/w/%d/h/%d",originImageURL,imageW,imageH];
            }else
            originImageURL = [NSString stringWithFormat:@"%@?imageView2/1/w/%d/h/%d",originImageURL,imageW*2,imageH*2];
        }
        
        } else if ([originImageURL containsString:@"aliyuncs.com"]){
            originImageURL = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,m_fill,h_250,w_250",originImageURL];
            
        }
    
//    if ([originImageURL hasPrefix:@"//"]) {//是否@"//"开头
//                                           //请求Url
//        originImageURL = [NSMutableString stringWithFormat:@"%@://%@",@"https",originImageURL];
//    }
    
        // 转义URL
    originImageURL = [originImageURL  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [self sd_setImageWithURL:[NSURL URLWithString:originImageURL] placeholderImage:placeholder completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (completedBlock) {
            completedBlock(image);
        }
    }];
}
/**
 * 加载图片，不加七牛参数
 */
- (void)fc_setImageWithURL:(NSString *)imageWithURL placeholder:(UIImage *)placeholder completed:(void (^)(UIImage *))completedBlock
{
    if ([imageWithURL isKindOfClass:[UIImage class]]) {
        self.image=(UIImage*)imageWithURL;
        if (completedBlock) {
            completedBlock((UIImage*)imageWithURL);
        }
        return;
    }
    if (!placeholder) {
//        if (self.image) {
////            placeholder =self.image;
//        }else{
            placeholder = [WJCDeployModel getDeployWithDeployKey:WJCDeployHeadImage];
//        }
        
    }
    if(![imageWithURL isUrl]){
        imageWithURL = [NSString stringWithFormat:@"%@%@",[WJCDeployModel  getDeployWithDeployKey:WJCDeployImageHeadUrl],imageWithURL];
    }else{
        
    }
    
    SDWebImageDownloader *manager = [SDWebImageDownloader sharedDownloader];
    
    NSArray *array = [saveSandBox getCookie];
    if (array&&array.count>0) {
        NSMutableString *str=[NSMutableString new];
        for (NSHTTPCookie *cookie in array) {
            [str appendString:[NSString stringWithFormat:@"%@=%@;",cookie.name,cookie.value]];
        }
        
    [manager setValue:str forHTTPHeaderField:@"Cookie"];
    }
    [manager setValue:@"Code=iOS" forHTTPHeaderField:@"Client-Info"];
    [manager setValue:[NSString stringWithFormat:@"Platform=iOS;VersionName=%@",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"]] forHTTPHeaderField:@"Client-msg"];
    [manager setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"] forHTTPHeaderField:@"Accept-Language"];
    [manager setValue:@"true" forHTTPHeaderField:@"useClientLang"];
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"]){
        [manager setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"] forHTTPHeaderField:@"Accept-Language"];
    }
    
    [self sd_setImageWithURL:[NSURL URLWithString:[imageWithURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:placeholder completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (completedBlock) {
            completedBlock(image);
        }
    }];
}

/**
 * 加载图片，不加七牛参数,带失败回调
 */
- (void)fc_setImageWithURL:(NSString *)imageWithURL placeholder:(UIImage *)placeholder completed:(void (^)(UIImage *))completedBlock failed:(void (^)(void))failedBlock
{
    if ([imageWithURL isKindOfClass:[UIImage class]]) {
        self.image=(UIImage*)imageWithURL;
        return;
    }
    SDWebImageDownloader *manager = [SDWebImageDownloader sharedDownloader];
    
    [manager setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"appLanguage"] forHTTPHeaderField:@"Accept-Language"];
    [manager setValue:@"true" forHTTPHeaderField:@"useClientLang"];
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"]){
        [manager setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"limitLanguage"] forHTTPHeaderField:@"Accept-Language"];
    }
//    if ([imageWithURL hasPrefix:@"//"]) {//是否@"//"开头
//        //请求Url
//        imageWithURL = [NSMutableString stringWithFormat:@"https:%@",imageWithURL];
//    }
//
    [self sd_setImageWithURL:[NSURL URLWithString:/*[*/imageWithURL /*stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]*/] placeholderImage:placeholder completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
        if (completedBlock) {
            completedBlock(image);
        }
        if (error && (![imageURL isEqual:[NSURL URLWithString:@""]] || imageURL == nil)){
            if (failedBlock){
                failedBlock();
            }
        }
    }];
}
-(void)startRotationAnimate{
 CABasicAnimation *layer = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
  layer.toValue = @(2*M_PI);
  layer.duration = 1;
  layer.removedOnCompletion = false;
  layer.repeatCount = MAXFLOAT;
  [self.layer addAnimation:layer forKey:nil];
}
- (void)stopRotationAnimate{
   [self.layer removeAllAnimations];
}
//-(void)setTapShowImg:(BOOL)tapShowImg{
//    objc_setAssociatedObject(self,@selector(tapShowImg),@(tapShowImg),OBJC_ASSOCIATION_ASSIGN);
//    if (tapShowImg==YES) {
//
//    }
//}
//-(BOOL)tapShowImg{
//    return objc_getAssociatedObject(self, _cmd);
//}
-(void)imageShow:(UITapGestureRecognizer*)sender{
 
    if([self.tapUrlPath isUrl]){
        [FCPhotoBrowserTool photoBrowserWithImages:self.tapUrlPaths.count>0&&[self.tapUrlPaths containsObject:self.tapUrlPath]?self.tapUrlPaths:@[self.tapUrlPath] sourceImageViews:nil currentIndex:self.tapUrlPaths.count>0&&[self.tapUrlPaths containsObject:self.tapUrlPath]?[self.tapUrlPaths indexOfObject:self.tapUrlPath]:0 showFromVC:[FCCGetCurrentVcTool getCurrentViewController]];

    }
}
-(void)setTapUrlPath:(NSString *)tapUrlPath{
    if ([tapUrlPath isKindOfClass:[NSString class]] &&tapUrlPath.length>0 && [[tapUrlPath substringToIndex:1] isEqual:@"/"]) {
        tapUrlPath =[NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployImageHeadUrl], [tapUrlPath substringFromIndex:1]];
    }
    else if([tapUrlPath isKindOfClass:[UIImage class]]){
    }
   else if (![tapUrlPath isUrl]) {
        tapUrlPath = [NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployImageHeadUrl],tapUrlPath];
    }
    if(tapUrlPath.length>5){
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap1=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageShow:)];
        tap1.numberOfTapsRequired=1;
        [self addGestureRecognizer:tap1];
    }
    objc_setAssociatedObject(self, @selector(tapUrlPath), tapUrlPath, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)tapUrlPath{
    return objc_getAssociatedObject(self, @selector(tapUrlPath));
}
-(void)setTapUrlPaths:(NSArray *)tapUrlPaths{
    NSMutableArray *arr = [NSMutableArray new];
    for (int i = 0; i<tapUrlPaths.count; i++) {
        if ([tapUrlPaths[i] isKindOfClass:[NSString class]]) {
            if( [[tapUrlPaths[i] substringToIndex:1] isEqual:@"/"]){
                [arr addObject:[tapUrlPaths[i] substringFromIndex:1]];
            }
            if (![tapUrlPaths[i] isUrl]) {
                 [arr addObject:[NSString stringWithFormat:@"%@%@",[WJCDeployModel getDeployWithDeployKey:WJCDeployImageHeadUrl],tapUrlPaths[i]]];
             }
        }
        if([tapUrlPaths[i] isKindOfClass:[UIImage class]]){
            [arr addObject:tapUrlPaths[i]];
        }
    }
    objc_setAssociatedObject(self, @selector(tapUrlPaths), arr, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSArray *)tapUrlPaths{
    return objc_getAssociatedObject(self, @selector(tapUrlPaths));
}
//-(void)setVoidBlock:(void (^)(void))voidBlock{
//    objc_setAssociatedObject(self, &voidKey, voidBlock, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
//}
//-(void (^)(void))voidBlock{
//    return objc_getAssociatedObject(self, &voidKey);
//}
@end
